package de.preissler.insertjoin;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

public class JMX
{
	private static final String PORT = "8080";
	
	private JMX() {};

	public static void clean(String host, String keyspace, String columnfamily)
	{
		try {
			flush(host, keyspace, columnfamily);
		} catch (Exception e1) {}
		
		try {
			Thread.sleep(500);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try {
			compact(host, keyspace, columnfamily);
		} catch (Exception e) {}
	}
	
	private static void flush(String host, String keyspace, String columnfamily) throws Exception
	{
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + PORT + "/jmxrmi");
        JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
        
        ObjectName on = new ObjectName("org.apache.cassandra.db:type=ColumnFamilies," +
        		"keyspace=" + keyspace + "," +
        		"columnfamily=" + columnfamily);
        
        mbsc.invoke(on, "forceFlush", null, null);
        
        jmxc.close();
	}
	
	private static void compact(String host, String keyspace, String columnfamily) throws Exception
	{
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + PORT + "/jmxrmi");
        JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
        
        ObjectName on = new ObjectName("org.apache.cassandra.db:type=ColumnFamilies," +
        		"keyspace=" + keyspace + "," +
        		"columnfamily=" + columnfamily);
        
        mbsc.invoke(on, "forceFlush", null, null);
        
        mbsc.invoke(on, "forceMajorCompaction", null, null);
        
        jmxc.close();
	}
}
